#import "GalleryViewController.h"
#import "GalleryTableViewCell.h"
#import "MJRefresh.h"
#import "AFAppClient.h"
#import "MyGalleryViewController.h"

@interface GalleryViewController ()<
    UITableViewDataSource,
    UITableViewDelegate,
    UIScrollViewDelegate,
    UITextFieldDelegate,
    UIActionSheetDelegate,
    UIImagePickerControllerDelegate,
    UINavigationControllerDelegate
>

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UIView *replyView;
@property (nonatomic, retain) UIButton *cameraButton;
@property (nonatomic, retain) UITextField *textField;
@property (nonatomic, retain) UIButton *pubButton;

@property (nonatomic, assign) CGFloat replyViewHeight;
@property (nonatomic, retain) NSMutableArray *data;
@property (nonatomic, copy) NSString *picPrefix;
@property (nonatomic, retain) UIImage *selectedImage;

@property (nonatomic, copy) void (^blockPubCallerySuccess)(NSDictionary *);

@end

@implementation GalleryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
        self.edgesForExtendedLayout = UIRectEdgeNone;
    [self _initNav];
    [self _initView];
    [self _initBlocks];
    [self _initData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [NOTIFICATION_CENTER addObserver:self
                            selector:@selector(keyboardWillShow:)
                                name:UIKeyboardWillShowNotification
                              object:nil];
    [NOTIFICATION_CENTER addObserver:self
                            selector:@selector(keyboardWillHide:)
                                name:UIKeyboardWillHideNotification
                              object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [NOTIFICATION_CENTER removeObserver:self
                                   name:UIKeyboardWillShowNotification
                                 object:nil];
    [NOTIFICATION_CENTER removeObserver:self
                                   name:UIKeyboardWillHideNotification
                                 object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)_initNav {
    
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.title = @"宝贝作品秀";
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 20 , 44, 44)];
    button.showsTouchWhenHighlighted = YES;
    button.backgroundColor = [UIColor clearColor];
    button.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
    [button setImage:[UIImage imageNamed:@"nav_btn_back"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backPage:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    UIButton *rightButton = [self createNavRightButton:@"相册" target:self action:@selector(openAlbum:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@""
                                   style:UIBarButtonItemStylePlain
                                   target:nil
                                   action:nil];
    self.navigationItem.backBarButtonItem=backButton;
}

- (void)_initView {

    _replyViewHeight = 48.0f;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, APP_SCREEN_WIDTH, APP_SCREEN_HEIGHT - _replyViewHeight - self.navHeight) style:UITableViewStyleGrouped];
    _tableView.backgroundColor = DefaultViewBackgroundColor;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    _replyView = [[UIView alloc] initWithFrame:CGRectMake(0, _tableView.bottom, APP_SCREEN_WIDTH, _replyViewHeight)];
    _replyView.backgroundColor = DefaultViewBackgroundColor;
    [self.view addSubview:_replyView];
    CALayer *borderTop = [CALayer layer];
    borderTop.backgroundColor = UIColorMake(213, 213, 213).CGColor;
    borderTop.frame = CGRectMake(0, 0, _replyView.width, 1);
    [_replyView.layer addSublayer:borderTop];
    CALayer *borderBottom = [CALayer layer];
    borderBottom.backgroundColor = UIColorMake(213, 213, 213).CGColor;
    borderBottom.frame = CGRectMake(0, _replyViewHeight - 1, _replyView.width, 1);
    [_replyView.layer addSublayer:borderBottom];
    
    UIButton *camera = [[UIButton alloc] initWithFrame:CGRectMake(5, (_replyViewHeight - 30) / 2, 32, 30)];
    [camera setImage:[UIImage imageNamed:@"gallery_btn_camera"] forState:UIControlStateNormal];
    camera.backgroundColor = [UIColor clearColor];
    camera.showsTouchWhenHighlighted = YES;
    [camera addTarget:self action:@selector(clickCameraButton:) forControlEvents:UIControlEventTouchUpInside];
    [_replyView addSubview:camera];
    _cameraButton = camera;
    
    _textField = [[UITextField alloc] initWithFrame:CGRectMake(camera.right + 5, camera.top, _replyView.width - camera.right - 5 - 75, 30)];
    _textField.placeholder = @"输入你的图片配文...";
    _textField.font = [UIFont systemFontOfSize:13.0f];
    _textField.layer.cornerRadius = 5.0f;
    _textField.layer.borderWidth = .5f;
    _textField.layer.borderColor = DefaultBorderColor.CGColor;
    _textField.delegate = self;
    _textField.returnKeyType = UIReturnKeyDone;
    _textField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, _textField.height)];
    _textField.leftViewMode = UITextFieldViewModeAlways;
    [_textField addTarget:self action:@selector(textChangeAction:) forControlEvents:UIControlEventEditingChanged];
    [_replyView addSubview:_textField];
    
    _pubButton = [[UIButton alloc] initWithFrame:CGRectMake(_replyView.width - 8 - 60, _textField.top, 60, _textField.height)];
    _pubButton.backgroundColor = UIColorMake(255, 110, 110);
    _pubButton.titleLabel.font = [UIFont systemFontOfSize:13.0f];
    _pubButton.layer.borderWidth = .5f;
    _pubButton.layer.borderColor = DefaultBorderColor.CGColor;
    _pubButton.layer.cornerRadius = 3.0f;
    [_pubButton setTitle:@"发送" forState:UIControlStateNormal];
    [_pubButton addTarget:self action:@selector(clickPubButton:) forControlEvents:UIControlEventTouchUpInside];
    _pubButton.showsTouchWhenHighlighted = YES;
    _pubButton.enabled = NO;
    _pubButton.alpha = .7f;
    [_replyView addSubview:_pubButton];
}

#pragma mark - Data

- (void)_initData {
   
    _data = [[NSMutableArray alloc] init];
    
    [self setUpRefreshPlugin];
}

- (void)dealData:(NSDictionary *)dic isReload:(BOOL)isReload {
    
    if (!dic || dic.count <=0 || ![dic isKindOfClass:[NSDictionary class]]) {
        return;
    }
    
    if (isReload) {
        [_data removeAllObjects];
    }
    
    NSLog(@"refresh data : %@", dic);
    
    _picPrefix = [NSString stringWithFormat:@"%@", dic[@"srcurl"]];
    for (NSDictionary *subDic in dic[@"works"]) {
       NSMutableDictionary *nsmDic = [[NSMutableDictionary alloc]init];
        [nsmDic setObject:[subDic objectForKey:@"uinfo"] forKey:@"uinfo"];
        [nsmDic setObject:[subDic objectForKey:@"time"] forKey:@"time"];
        [nsmDic setObject:[subDic objectForKey:@"title"] forKey:@"title"];
        [nsmDic setObject:[subDic objectForKey:@"srcurl"] forKey:@"srcurl"];
        [nsmDic setObject:[subDic objectForKey:@"praise"] forKey:@"praise"];
        [nsmDic setObject:[subDic objectForKey:@"width"] forKey:@"width"];
        [nsmDic setObject:[subDic objectForKey:@"height"] forKey:@"height"];
        [nsmDic setObject:[subDic objectForKey:@"has_my_prize"] forKey:@"isloved"];
        [nsmDic setObject:[subDic objectForKey:@"id"] forKey:@"id"];
        [_data addObject:nsmDic];
    }
    
    [_tableView reloadData];
}

#pragma mark - Networking

- (BOOL)apiGetData:(NSString*)requestType baseId:(NSString *)baseId{
    NSString* uid = [NSString stringWithFormat:@"%ld",[[UserDao getInstance] getUserId]];
    NSString* utype = @"1";
    
    NSDictionary *temp_dict = @{@"uid":uid,
                                @"utype":utype,
                                @"token":[[UserDao getInstance]getAccessToken],
                                @"dir":requestType,
                                @"baseid":baseId};
    
    NSString *dataString = [JsonUtil convertDictionaryToJson:temp_dict];
    
    NSString *msg = @"PARENT_GET_WORKS";
    
    PopUIManager *popUIMgr = [PopUIManager getInstanse];
    [popUIMgr showWaitingUI:self.view];
    
    [[NetWorkManager getInstanse] requestURLAsynMessage:msg data:dataString FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        if ([requestType isEqualToString:@"new"]) {
            [self stopHeaderRefresh];
        }else if ([requestType isEqualToString:@"old"]){
            [self stopFooterRefresh];
        }
        
        if (connectionError) { //连接失败
            NSLog(@"Http Error: %@   %ld", connectionError.localizedDescription,(long)connectionError.code);
            NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)connectionError.code];
            [popUIMgr popAlertView:nil title:@"提示" message:error_content cancelButtonTitle:@"确定"];
        }else{//连接成功，判断是否有数据返回
            if (data) {
                NSDictionary *dict = [JsonUtil convertDataToDictionary:data];
                if ([[dict objectForKey:@"retCode"] integerValue] == 1) {
                    if ([requestType isEqualToString:@"new"]) { //下拉 获取最新数据的回调
                        [self dealData:dict isReload:YES];
                    }else if ([requestType isEqualToString:@"old"]){//上拉 加载更多旧数据的回调
                        [self dealData:dict isReload:NO];
                    }
                }else if ([[dict objectForKey:@"retCode"] integerValue]== 10020) {
                    if ([requestType isEqualToString:@"new"]) { //下拉 获取最新数据的回调
                        [popUIMgr popAlertView:nil title:@"提示" message:@"还没有数据哦~" cancelButtonTitle:@"确定"];
                    }else if ([requestType isEqualToString:@"old"]){//上拉 加载更多旧数据的回调
                        [popUIMgr popAlertView:nil title:@"提示" message:@"没有更多了哦~" cancelButtonTitle:@"确定"];
                    }
                }else{
                    [popUIMgr popAlertView:nil title:@"提示" message:@"还没有数据哦~" cancelButtonTitle:@"确定"];
                }
            }else{
                [popUIMgr popAlertView:nil title:@"提示" message:@"服务器没有返回数据" cancelButtonTitle:@"确定"];
            }
        }
        [popUIMgr removeWaitingUI];
    }];
    return YES;
}

#pragma mark - AFNetworking Block

- (void)_initBlocks {
    
    WS(weakSelf);
    
    self.blockPubCallerySuccess = ^(NSDictionary *response){
        __strong typeof (weakSelf) strongSelf = weakSelf;
        if (!strongSelf) {
            return;
        }
        
        if ([[NSString stringWithFormat:@"%@", response[@"retCode"]] isEqualToString:@"1"]) {
            
            [strongSelf showHudComplete:@"发表成功" success:YES];
            [strongSelf.textField resignFirstResponder];
            [strongSelf headerRereshing];
            [strongSelf.cameraButton setImage:[UIImage imageNamed:@"gallery_btn_camera"] forState:UIControlStateNormal];
            strongSelf.selectedImage = nil;
            strongSelf.textField.text = @"";
        }else {
            [strongSelf showHudComplete:@"发表失败" success:NO];
            [strongSelf.textField resignFirstResponder];
        }
    };
}

#pragma mark - Private Methods

- (BOOL)checkCamera {
    
    BOOL isCamera = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
    if(!isCamera) {
        [self ShowExclaHud:@"此设备没有摄像头"];
        return NO;
    }else{
        return YES;
    }
}

/**
 *  集成刷新控件
 */
#pragma mark - MJRefresh

- (void)setUpRefreshPlugin {
    
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //#warning 自动刷新(一进入程序就下拉刷新)
    [_tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    //设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    _tableView.headerPullToRefreshText = @"下拉刷新";
    _tableView.headerReleaseToRefreshText = @"松开刷新";
    _tableView.headerRefreshingText = @"正在刷新...";
    
    _tableView.footerPullToRefreshText = @"上拉加载";
    _tableView.footerReleaseToRefreshText = @"松开加载";
    _tableView.footerRefreshingText = @"正在加载...";
}

//================顶部刷新，获取最新动态=========================
//首次进入会自动执行一次获取最新动态
- (void)headerRereshing
{
    if ([NetWorkManager connectedToNetwork]) {

        [self apiGetData:@"new" baseId:@"-1"];
    }else{
        //没有网络的情况下，加载本地缓存数据
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络连接断开" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
}

//================底部刷新，获取最新动态=========================
- (void)footerRereshing
{
    
    if([NetWorkManager connectedToNetwork]) {
        NSString *baseId = [NSString stringWithFormat:@"%@", ((NSDictionary *)_data.lastObject)[@"id"]];
        NSLog(@"%@", baseId);
        [self apiGetData:@"old" baseId:baseId];

    }else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络连接断开" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
}

-(void) stopHeaderRefresh {
    
    [self.tableView headerEndRefreshing];
}

-(void) stopFooterRefresh {
    
    [self.tableView footerEndRefreshing];
}

#pragma mark - NOTIFICATION_CENTER
- (void)keyboardWillShow:(NSNotification *)notification {
    
    NSValue *keyboardValue = [notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect frame = [keyboardValue CGRectValue];
    
    [UIView animateWithDuration:0.5f
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^(void){
                         _replyView.top = APP_SCREEN_HEIGHT - frame.size.height - _replyView.height - self.navHeight;
                     }
                     completion:^(BOOL finished){
                     }];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    
    [UIView animateWithDuration:0.2f
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^(void){
                         _replyView.top = _tableView.bottom;
                     }
                     completion:^(BOOL finished){}];
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    return 7.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {

    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat picHeight = 0.0f;
    NSDictionary *gallery = _data[indexPath.section];
    CGFloat width = [gallery[@"width"] floatValue] ? : 1.0f;
    CGFloat heigth = [gallery[@"height"] floatValue];
    CGFloat scale = heigth / width;
    picHeight = scale * APP_SCREEN_WIDTH;
    
    return 134 + picHeight;//134为除图片外的其他元素高度
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    NSLog(@"post:%@", _data[indexPath.section]);

}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return _data.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"CellStyleMyPost";
    
    GalleryTableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil) {
        cell = [[GalleryTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.backgroundColor = [UIColor whiteColor];
    }
    
    cell.picPrefix = _picPrefix;
    cell.floorIndex = indexPath.section;
    cell.data = _data[indexPath.section];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    if (scrollView == _tableView) {
        [_textField resignFirstResponder];
    }
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [_textField resignFirstResponder];
    
    return YES;
}

- (void)textChangeAction:(UITextField *)textField {

    if (textField.text.length > 0) {
        _pubButton.enabled = YES;
        _pubButton.alpha = 1.0f;
    }else {
        _pubButton.enabled = NO;
        _pubButton.alpha = .7f;
    }
}

#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    UIImagePickerControllerSourceType sourceType;
    if(buttonIndex == 0) {
        if([self checkCamera]){
            sourceType = UIImagePickerControllerSourceTypeCamera;
            [self openGallery:sourceType];
        }else{
            return;
        }
    }else if(buttonIndex == 1){
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self openGallery:sourceType];
    }
}

-(void)openGallery:(UIImagePickerControllerSourceType)source {

    UIImagePickerController *pick = [[UIImagePickerController alloc] init];
    pick.sourceType = source;
    pick.delegate = self;
    [self presentViewController:pick animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController: (UIImagePickerController *)picker didFinishPickingMediaWithInfo: (NSDictionary *)info {
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    _selectedImage = image;
    [_cameraButton setImage:image forState:UIControlStateNormal];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void) imagePickerControllerDidCancel: (UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - Action

- (void)backPage:(id)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)openAlbum:(id)sender {

    MyGalleryViewController *myGallery = [[MyGalleryViewController alloc] init];
    [self.navigationController pushViewController:myGallery animated:YES];
}

- (void)clickCameraButton:(id)sender {

    NSLog(@"click camera");
    UIActionSheet *menu = [[UIActionSheet alloc]
                           initWithTitle: @""
                           delegate:self
                           cancelButtonTitle:@"取消"
                           destructiveButtonTitle:nil
                           otherButtonTitles:@"拍照",@"图库相册", nil];
    [menu showInView:self.view];
}

- (void)clickShareButton:(UIButton *)button {

    NSLog(@"share:%ld", (long)button.tag);
}

- (void)clickLoveButton:(UIButton *)button {

    NSLog(@"love:%ld", (long)button.tag);
    NSUInteger data_index = button.tag;
    NSMutableDictionary *dict1 = [self.data objectAtIndex:data_index];
    debugLog(@"%@",dict1);
    NSUInteger pid = [[dict1 objectForKey:@"id"] integerValue];
    
    NSString* uid = [NSString stringWithFormat:@"%ld",[[UserDao getInstance] getUserId]];
    NSString* utype = @"1";
    
    NSDictionary *temp_dict = @{@"uid":uid,
                                @"utype":utype,
                                @"token":[[UserDao getInstance]getAccessToken],
                                @"workid":@(pid)
                                };
    
    NSString *dataString = [JsonUtil convertDictionaryToJson:temp_dict];
    
    PopUIManager *popUIMgr = [PopUIManager getInstanse];
    [popUIMgr showWaitingUI:self.view];
    
    [[NetWorkManager getInstanse] requestURLAsynMessage:PARENT_PRAISE_WORK data:dataString FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        [popUIMgr removeWaitingUI];
        if (connectionError) { //连接失败
            NSLog(@"Http Error: %@   %ld", connectionError.localizedDescription,(long)connectionError.code);
            NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)connectionError.code];
            [popUIMgr popAlertView:nil title:@"提示" message:error_content cancelButtonTitle:@"确定"];
        }else{//连接成功，判断是否有数据返回
            if (data) {
                NSDictionary *dict = [JsonUtil convertDataToDictionary:data];
                if ([[dict objectForKey:@"retCode"] integerValue] == 1) {
                    [self ShowExclaHud2:@"点赞成功~"];
                    NSUInteger praise = [[dict1 objectForKey:@"praise"]integerValue];
                    praise = praise+1;
                    [dict1 setValue:@(praise) forKey:@"praise"];
                    [dict1 setValue:@(1) forKey:@"isloved"];
                    [self.tableView reloadData];
                }else{
                    [self ShowExclaHud:@"已点赞!"];
                }
            }else{
                [popUIMgr popAlertView:nil title:@"提示" message:@"服务器没有返回数据" cancelButtonTitle:@"确定"];
            }
        }
        }];

}

- (void)clickPubButton:(UIButton *)button {

    if (!_selectedImage) {
        [self ShowExclaHud:@"请选择要上传的图片"];
        return;
    }
    
    NSLog(@"pub");
    NSDictionary *params = @{
                             @"uid":@([[UserDao getInstance]getUserId]),
                             @"utype":@(1),
                             @"token":[[UserDao getInstance]getAccessToken],
                             @"message":@"PARENT_SEND_WORK",
                             @"title":_textField.text,
                             @"pic0":_selectedImage
                             };
    
    [super showHud:@"发表中" isDim:YES];
    
    [[AFAppClient sharedManager] postWithURL:SERVER_URL withParameters:params success:self.blockPubCallerySuccess failure:nil];
}

@end
